package Thread;

import java.sql.Time;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName interview
 * @Description: TODO
 * @date ${DAT}18:30
 */
public class PC {
}

class MyResource{
    private volatile boolean FLAG = true;
    private AtomicInteger num = new AtomicInteger(0);
    BlockingQueue<String> blockingQueue = null;

    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }

    public void stop(){
        FLAG = false;
    }

    public void myPro() throws InterruptedException {
        String data = null;
        boolean resValue;
        while (FLAG){
            data = num.incrementAndGet()+"";
            resValue = blockingQueue.offer(data,2L, TimeUnit.SECONDS);
            if (resValue){
                System.out.println("生产者"+Thread.currentThread().getName()+"成功生成"+num.get()+"的物品");
            }else {
                System.out.println("生产者生成失败");
            }
            TimeUnit.SECONDS.sleep(1);
        }
        System.out.println("老板叫停");
    }

    public void myCon() throws InterruptedException {
        String reslut = null;
        while (FLAG){
            reslut = blockingQueue.poll(2L, TimeUnit.SECONDS);
            if (reslut == null || reslut.equalsIgnoreCase("")){
                FLAG = false;
                System.out.println(Thread.currentThread().getName()+"\t超过获取规定的时间");
                return;
            }
            System.out.println(Thread.currentThread().getName()+"\t消息队列蛋糕"+reslut+"成功");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyResource resource = new MyResource(new ArrayBlockingQueue<>(10));
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"生成线程启动");
            try {
                resource.myPro();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"消费者线程启动");
            try {
                resource.myCon();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B").start();

        TimeUnit.SECONDS.sleep(5);
        resource.stop();
    }
}